package com.example.protocol.mqtt;

import com.example.protocol.mqtt.handler.CabinetCmdReturnHandler;
import com.example.protocol.mqtt.handler.CabinetOfflineHandler;
import com.example.protocol.mqtt.handler.CabinetStateHandler;
import com.example.protocol.mqtt.handler.PhoneChangePowerRequestHandler;
import com.example.protocol.service.IBatteryDataService;
import com.example.protocol.service.ICabinetDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * 此类在springboot程序加载完成自动就会运行，因为实现了ApplicationRunner接口
 * 此类的目的是让程序启动后就自动实例化mqtt客户端，并订阅相应的topic
 */
@Component
@Slf4j
public class MQTTRunner implements ApplicationRunner {

    @Value("${spring.datasource.url}")
    String url;

    @Autowired
    MQTTClient mqttClient;

    @Autowired
    ICabinetDataService cabinetDataService;

    @Autowired
    IBatteryDataService batteryDataService;

    static List<CallBackHandler> subscribeTopicHandlerList; // 处理各topic的handler的List

    @PostConstruct //PostConstruct表示在构造之后执行，这样Autowired的各个Service就不会是null
    public void MQTTRunnerInit() {
        subscribeTopicHandlerList = new ArrayList<>();
        subscribeTopicHandlerList.add(new CabinetStateHandler(cabinetDataService, batteryDataService));
        subscribeTopicHandlerList.add(new CabinetOfflineHandler());
        subscribeTopicHandlerList.add(new PhoneChangePowerRequestHandler());
        subscribeTopicHandlerList.add(new CabinetCmdReturnHandler());
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        log.info(url);
        mqttClient.publishMessage("cabinet/1/cmd", "open the door");
        // 订阅各topic
        for (CallBackHandler handler : subscribeTopicHandlerList) {
            mqttClient.subscribeMessage(handler.getHandleableTopic());
        }

//        cabinetDataService.save(null);

    }


}
